package com.qiantu.phone.ui.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.base.DensityUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.manager.FlowLayoutManager;
import com.qiantu.phone.ui.adapter.DeviceFilterItemAdapter;
import com.qiantu.phone.ui.adapter.RoomFloorDialogAdapter;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class BottomDeviceFilterDialog extends BottomPopupView implements View.OnClickListener {
    public static final int TYPE_SCENE = 1;
    public static final int TYPE_DEVICE = 2;
    public static final int AVAILABLE_DEVICE = 12;
    public static final int TRIGGER_DEVICE = 13;
    public static final int ACTION_DEVICE = 14;
    public static final int GROUP_DEVICE = 15;

    private ImageView close;
    private RecyclerView tabRecyclerView;
    private boolean allIsSelect = true;
    private RecyclerView floorRoomList;
    private TextView btnReset;
    private TextView btnComplete;
    private RoomFloorDialogAdapter mAdapter;
    private Map<String, RoomBean> mSelectArea = new LinkedHashMap<>();
    private Map<String, RoomBean> mSaveArea = new LinkedHashMap<>();
    private List<FloorBean> mFloorBeans;
    //1 场景 2 设备
    private int type;
    //设备大类
    private String deviceMainType;
    //设备小类
    private String deviceType;
    //初始场景或者设备数量
    private int mInitCount;
    private int deviceCategory;
    //是否停启用
    private Boolean isDisable;
    //是否常用
    private Boolean isFavourite;
    //是否首页显示
    private Boolean isHomePage;
    private DeviceFilterItemAdapter mDeviceFilterItemAdapter;

    public BottomDeviceFilterDialog(@NonNull Context context, int type) {
        super(context);
        this.type = type;
    }

    public BottomDeviceFilterDialog(@NonNull Context context, int type , int deviceCategory, String deviceMainType) {
        super(context);
        this.type = type;
        this.deviceMainType = deviceMainType;
        this.deviceCategory = deviceCategory;
    }

    public BottomDeviceFilterDialog(@NonNull Context context, int type , int deviceCategory, String deviceMainType,String deviceType) {
        super(context);
        this.type = type;
        this.deviceType = deviceType;
        this.deviceCategory = deviceCategory;
    }

    public BottomDeviceFilterDialog(@NonNull Context context, int type, int deviceCategory) {
        super(context);
        this.type = type;
        this.deviceCategory = deviceCategory;
    }

    public void setInitCount(int count) {
        this.mInitCount = count;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_device_filter;
    }

    // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
    @Override
    protected void onCreate() {
        super.onCreate();
        close = findViewById(R.id.close);
        close.setOnClickListener(this);
        tabRecyclerView = findViewById(R.id.tab_recycler_view);
        floorRoomList = findViewById(R.id.floor_room_list);
        btnReset = findViewById(R.id.btn_reset);
        btnComplete = findViewById(R.id.btn_complete);
        btnReset.setOnClickListener(this::onClick);
        btnComplete.setOnClickListener(this::onClick);
//        btnComplete.setText(R.string.ok);
//        all.setText(type == TYPE_SCENE ? R.string.unlimited_area : R.string.all);
        tabRecyclerView.setLayoutManager(new FlowLayoutManager(getContext(), true));
        mDeviceFilterItemAdapter = new DeviceFilterItemAdapter(getContext());
        tabRecyclerView.setAdapter(mDeviceFilterItemAdapter);
        floorRoomList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new RoomFloorDialogAdapter(getContext()) {
            @Override
            public void onSelectChanged(Map<String, RoomBean> selectBean) {
                mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_ALL, false);
                setTitle(null);
            }
        };
        mAdapter.setData(mFloorBeans);
        floorRoomList.setAdapter(mAdapter);
        List<Integer> tabTypes = new ArrayList<>();
        switch (deviceCategory){
            case AVAILABLE_DEVICE:
            case TRIGGER_DEVICE:
            case ACTION_DEVICE:
            case GROUP_DEVICE:
                //设置默认启用
                isDisable = false;
                //停启用不可选
                tabTypes.add(DeviceFilterItemAdapter.ITEM_ALL);
                tabTypes.add(DeviceFilterItemAdapter.ITEM_IS_FAVOURITE);
                tabTypes.add(DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW);
                mDeviceFilterItemAdapter.setData(tabTypes);
                break;
            default:
                tabTypes.add(DeviceFilterItemAdapter.ITEM_ALL);
                tabTypes.add(DeviceFilterItemAdapter.ITEM_IS_DISABLE);
                tabTypes.add(DeviceFilterItemAdapter.ITEM_IS_FAVOURITE);
                tabTypes.add(DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW);
                mDeviceFilterItemAdapter.setData(tabTypes);
                isDisable = null;
                break;
        }
        mDeviceFilterItemAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                Integer type = mDeviceFilterItemAdapter.getData().get(position);
                if(type != null && type == DeviceFilterItemAdapter.ITEM_ALL){
                    checkAll();
                }
            }
        });
        mDeviceFilterItemAdapter.setOnChildClickListener(R.id.btn1, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                Integer type = mDeviceFilterItemAdapter.getData().get(position);
                switch (type){
                    case DeviceFilterItemAdapter.ITEM_IS_DISABLE://已启用
                        isDisable = false;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_DISABLE, false);
                        break;
                    case DeviceFilterItemAdapter.ITEM_IS_FAVOURITE://常用
                        isFavourite = true;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_FAVOURITE, true);
                        break;
                    case DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW://首页出现
                        isHomePage = true;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW, true);
                        break;
                }
            }
        });

        mDeviceFilterItemAdapter.setOnChildClickListener(R.id.btn2, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                Integer type = mDeviceFilterItemAdapter.getData().get(position);
                switch (type){
                    case DeviceFilterItemAdapter.ITEM_IS_DISABLE://已停用
                        isDisable = true;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_DISABLE, true);
                        break;
                    case DeviceFilterItemAdapter.ITEM_IS_FAVOURITE://非常用
                        isFavourite = false;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_FAVOURITE, false);
                        break;
                    case DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW://首页隐藏
                        isHomePage = false;
                        mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_IS_HOME_SHOW, false);
                        break;
                }
            }
        });
    }

    @Override
    protected void onShow() {
        super.onShow();
    }

    @Override
    protected void beforeShow() {
        super.beforeShow();
        initSelectState();
    }

    private void initSelectState() {
        mSelectArea.clear();
        mSelectArea.putAll(mSaveArea);
        mAdapter.setSelectMap(mSelectArea);
        if(mDeviceFilterItemAdapter != null){
            mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_ALL, allIsSelect);
        }
        setTitle(mInitCount);
    }

    public BottomDeviceFilterDialog setFloorBeans(List<FloorBean> data) {
        mFloorBeans = data;
        if (mAdapter != null) {
            mAdapter.setData(data);
        }
        return this;
    }

    // 设置最大宽度，看需要而定
    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }

    // 设置最大高度，看需要而定
    @Override
    protected int getMaxHeight() {
        return super.getMaxHeight();
    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return XPopupUtils.getAppWidth(getContext());
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return  XPopupUtils.getAppHeight(getContext()) - DensityUtils.dip2px(getContext(), 200);
    }

    private void checkAll(){
        if (!mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL)) {
            mDeviceFilterItemAdapter.setSelected(DeviceFilterItemAdapter.ITEM_ALL, true);
            mAdapter.clearSelected();
            switch (deviceCategory){
                case AVAILABLE_DEVICE:
                case TRIGGER_DEVICE:
                case ACTION_DEVICE:
                case GROUP_DEVICE:
                    isDisable = false;
                    break;
                default:
                    isDisable = null;
                    break;
            }
            isFavourite = null;
            isHomePage = null;
            setTitle(null);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_complete) {
            mSaveArea.clear();
            mSaveArea.putAll(mSelectArea);
            allIsSelect = mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL);
            if (type == TYPE_SCENE) {
                onSave(getAllSceneFormSelectArea());
            } else {
                confirm();
            }
            dismiss();
        } else if (id == R.id.close) {
            dismiss();
        } else if (id == R.id.btn_reset) {
            checkAll();
        }
    }

    private void confirm(){
        if(getContext() != null && getContext() instanceof AppActivity){
            ((AppActivity)getContext()).showDialog();
        }
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = getAllDeviceFormSelectArea();
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        if(getContext() instanceof AppActivity){
                            ((AppActivity)getContext()).hideDialog();
                        }
                        onConfirm(!mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL), devices);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

//    private List<SceneBean> getAllSceneFormSelectArea() {
//        if (all.isSelected()) {
//            return LLSceneDBManager.getInstance(getContext()).getAll();
//        }
//        ArrayList<SceneBean> result = new ArrayList<>();
//        if (commonArea.isSelected()) {
//            result.addAll(LLSceneDBManager.getInstance(getContext()).getCommonScenes());
//        }
//        if (mSelectArea == null || mSelectArea.isEmpty()) return result;
//        for (String roomSerialNo : mSelectArea.keySet()) {
//            result.addAll(mSelectArea.get(roomSerialNo).getSences());
//        }
//        return result;
//    }

    public List<SceneBean> getAllSceneFormSelectArea() {
        if (mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL)) {
            return LLSceneDBManager.getInstance(getContext()).getAll();
        }
        List<String> roomSerialNos = new ArrayList<>();
        if (mSelectArea != null){
            for (String roomSerialNo : mSelectArea.keySet()) {
                roomSerialNos.add(roomSerialNo);
            }
        }
        return LLSceneDBManager.getInstance(getContext()).getScenesForRoomSerialNos(roomSerialNos);
    }

    public List<DeviceBean> getAllDeviceFormSelectArea() {
        if (mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL)) {
            switch (deviceCategory){
                case TRIGGER_DEVICE:
                    return LLDeviceDBManager.getInstance(getContext()).getTriggerDevices(isDisable, isFavourite, isHomePage);
                case ACTION_DEVICE:
                    return LLDeviceDBManager.getInstance(getContext()).getActionDevices(isDisable, isFavourite, isHomePage);
                case GROUP_DEVICE:
                    return LLDeviceDBManager.getInstance(getContext()).getGroupDevices(deviceMainType,isDisable, isFavourite, isHomePage);
                default:
                    //AVAILABLE_DEVICE时isDisable默认设置成了false
                    if(!TextUtils.isEmpty(deviceMainType)){
                        return LLDeviceDBManager.getInstance(getContext()).getDeviceByMainType(deviceMainType, isDisable, isFavourite, isHomePage);
                    }else if(!TextUtils.isEmpty(deviceType)){
                        return LLDeviceDBManager.getInstance(getContext()).getDeviceByDeviceType(deviceType, isDisable, isFavourite, isHomePage);
                    }else{
                        return LLDeviceDBManager.getInstance(getContext()).getAll(isDisable, isFavourite, isHomePage);
                    }
            }
        }
        List<String> roomSerialNos = new ArrayList<>();
        if(mSelectArea != null){
            for (String roomSerialNo : mSelectArea.keySet()) {
                roomSerialNos.add(roomSerialNo);
            }
        }
        switch (deviceCategory){
            case TRIGGER_DEVICE:
                return LLDeviceDBManager.getInstance(getContext()).getTriggerDevicesByRoomSerialNos(roomSerialNos, isDisable, isFavourite, isHomePage);
            case ACTION_DEVICE:
                return LLDeviceDBManager.getInstance(getContext()).getActionDevicesByRoomSerialNos(roomSerialNos, isDisable, isFavourite, isHomePage);
            case GROUP_DEVICE:
                return LLDeviceDBManager.getInstance(getContext()).getGroupDevicesByRoomSerialNos(roomSerialNos, deviceMainType,isDisable, isFavourite, isHomePage);
            default:
                //AVAILABLE_DEVICE时isDisable默认设置成了false
                if(!TextUtils.isEmpty(deviceMainType)){
                    return LLDeviceDBManager.getInstance(getContext()).getDevicesByMainTypeAndRoomSerialNos(deviceMainType, roomSerialNos, isDisable, isFavourite, isHomePage);
                }else if(!TextUtils.isEmpty(deviceType)){
                    return LLDeviceDBManager.getInstance(getContext()).getDevicesByDeviceTypeAndRoomSerialNos(deviceType, roomSerialNos, isDisable, isFavourite, isHomePage);
                }else{
                    return LLDeviceDBManager.getInstance(getContext()).getDevicesByRoomSerialNos(roomSerialNos, isDisable, isFavourite, isHomePage);
                }
        }
    }

    public void setTitle(Integer size) {
        StringBuilder result = new StringBuilder();
        if (mDeviceFilterItemAdapter.getSelected().get(DeviceFilterItemAdapter.ITEM_ALL)) {
            result.append(type == TYPE_SCENE ? getResources().getString(R.string.unlimited_area) : getResources().getString(R.string.all_device));
        } else {
            if (mSelectArea != null && !mSelectArea.isEmpty()) {
                for (String roomSerialNo : mSelectArea.keySet()) {
                    if (result.length() == 0) {
                        result.append(mSelectArea.get(roomSerialNo).getRoomName());
                    } else {
                        result.append("、").append(mSelectArea.get(roomSerialNo).getRoomName());
                    }
                }
            }
        }
//        int size = type == TYPE_SCENE ? getAllSceneFormSelectArea().size() : getAllDeviceFormSelectArea().size();
        if (size != null) {
            result.append(" (").append(size).append(")");
        } else {
            result.append(" (").append(mInitCount).append(")");
        }
//        selectAreas.setText(result.toString());
    }

    public boolean isAllAreaIsSelect() {
        return allIsSelect;
    }

    public Map<String, RoomBean> getSelectArea() {
        return mSelectArea;
    }

    public void onSave(List<SceneBean> result) {
    }

    public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
    }
}
